<?php


namespace api\home\controller;


use api\home\model\SmsModel;
use api\home\model\UserModel;
use api\home\validata\UserValidata;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Config;
use think\facade\Filesystem;
use think\Request;

class UserController extends RestBaseController
{

    //发送验证码
    public function sendcode()
    {
        $mobile = input('mobile');
        //发验证码
        sendAliSms($mobile);
    }

    //注册
    public function register()
    {

        //接收参数
        $data = input('post.');

        //验证器验证
        $validate = new UserValidata();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        // 验证用户是否存在
        $user = UserModel::where('mobile','=',$data['mobile'])->find();
        if($user){
            $this->error('用户已存在');
        }

        //验证码验证
        checkSms($data['mobile'], $data['code']);

        //添加
        if(UserModel::create($data)){
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }

    }

    //登录
    public function login()
    {
        //接收
        $mobile = input('mobile');
        $code = input('code');

        //验证
        if(empty($mobile)){
            $this->error('电话不存在');
        }
        if(empty($code)){
            $this->error('验证码不存在');
        }

        $data = UserModel::where('mobile','=',$mobile)->find();
        if(empty($data)){
            $this->error('手机号错误');
        }

        $sms = SmsModel::where('mobile','=',$mobile)->find();
      //  halt($sms);

        if(checkSms($mobile,$sms['code'])){
            $token = signToken($data['id'],$mobile);
            $this->success('登陆成功', ['data' => $token]);
        }else{
            $this->error('登录失败');
        }

    }

    //用户列表显示
    public function getUserList(Request $request)
    {

        $user = UserModel::field('id,image,user_name,mobile')
            ->where('id',$request->userId)
            ->find();
        $user['image'] = request()->domain() . '/stroge/' .$user['image'];

        $this->success('用户列表',$user);
    }



    //修改个人信息
    public function updateUser(Request $request)
    {
        //获取信息
        $data = input('post.');
        $data['user_id'] = $request->userId;

        //验证查询信息
        $edit = UserModel::find($request->userId);
        if(!$edit){
            $this->error('未查询到信息');
        }

        //修改信息
        $upload = UserModel::where('user_id','=',$request->userId)
            ->update($data);
        if($upload){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }


}